terraform {
  required_providers {
    huaweicloud = {
      source = "local-registry/huaweicloud/huaweicloud"
      version = "= 1.34.1"
    }
  }
}
provider "huaweicloud" {  
  region     = "cn-north-4"
  access_key = ""
  secret_key = ""
}

# Get Image 
data "huaweicloud_images_image" "image" {
  name_regex   = ".*COPY_new_HW_windows2016_standard_64bit_ch_20210727$"
  os = "Windows"
  os_version = "Windows Server 2016 Standard 64bit"
}

#Get Default VPC
data "huaweicloud_vpcs" "default" {}

#Get Default Subnet
data "huaweicloud_vpc_subnet_ids" "default" {
  vpc_id = data.huaweicloud_vpcs.default.vpcs[0].id
}

#Get Default Secgroup
data "huaweicloud_networking_secgroup" "default" {
  name    = "default"
}

#Create ECS
resource "huaweicloud_compute_instance" "instance" {
  name     = var.ecs_name
  image_id = data.huaweicloud_images_image.image.id
  flavor_id = "c6.large.2"
  admin_pass = var.ecs_admin_pass
  network {
    uuid   =  data.huaweicloud_vpc_subnet_ids.default.ids[0]
  }
  system_disk_type = "SAS"
  system_disk_size = 40
  charging_mode     = "postPaid"
  security_group_ids   = [data.huaweicloud_networking_secgroup.default.id]
  user_data         =  file("./border.ps1")
}

resource "huaweicloud_vpc_eip" "eip" {
  publicip {
    type = "5_bgp"
  }
  bandwidth {
    name        = "${var.template_name}_bandwith"
    size        = 1
    share_type  = "PER"
    charge_mode = "traffic"
  }
}

resource "huaweicloud_compute_eip_associate" "associated" {
  depends_on = [huaweicloud_vpc_eip.eip,huaweicloud_compute_instance.instance]
  public_ip   = huaweicloud_vpc_eip.eip.address
  instance_id = huaweicloud_compute_instance.instance.id
}
